package com.konsung.ksdc.manager.community;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ibm.mqtt.MqttException;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.bean.MqttMsgNotice;
import com.konsung.ksdc.bean.netbean.GroupNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.mqtt.MqttMsgUtils;
import com.konsung.ksdc.common.mqtt.parser.RequestDeleteGroupMessageHandler;
import com.konsung.ksdc.common.mqtt.parser.RequestGroupReceivedMessageHandler;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.ActivityCollector;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DateUtils;
import com.konsung.ksdc.common.utils.ImageUtils;
import com.konsung.ksdc.common.utils.PhotoUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.ConfirmPopupWindow;
import com.konsung.ksdc.common.widget.LineEditText;
import com.konsung.ksdc.common.widget.PermissionPopupWindow;
import com.konsung.ksdc.common.widget.TakePicBottomPop;
import com.konsung.ksdc.common.widget.WaitingDialog;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.user.QRCodeActivity;
import com.konsung.ksdc.service.MqttService;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by liangkun on 2017/5/5 0005.
 * 群好友信息
 */

public class GroupMemberActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String GROUPID = "groupId";
    private static final String KSKF = "kskf";
    private static final String KSBK = "ksbk";
    @Bind(R.id.tv_group_name)
    TextView tvGroupName; // 群聊名称
    @Bind(R.id.tv_check_all)
    RelativeLayout tvCheckAll; // 查看全部成员
    @Bind(R.id.rl_add_group)
    RelativeLayout rlAddContact; // 添加好友列表按钮
    @Bind(R.id.rl_remove_group)
    RelativeLayout rlDownContact; // 移除好友列表按钮
    @Bind(R.id.ll_group_name)
    LinearLayout llGroupName; // 群聊名称
    @Bind(R.id.ll_modify_container)
    LinearLayout llModifyContainer; // 修改群聊 \
    @Bind(R.id.et_modify_name)
    LineEditText editText; // 修改群聊
    @Bind(R.id.rl_group_qr)
    RelativeLayout rlGroupQr; // 二维码
    @Bind(R.id.rl_group_head)
    RelativeLayout rlGroupHead; // 群头像
    @Bind(R.id.gv_group_allmembers)
    GridView gvGroupMembers; // 群成员列表
    @Bind(R.id.ll_member_container)
    LinearLayout llIndexContainer; // 群资料容器
    @Bind(R.id.ll_contact_container)
    LinearLayout llContactContainer; // 好友列表容器
    @Bind(R.id.lv_contact)
    ListView lvContact; // 好友列表
    @Bind(R.id.img_contact_back)
    ImageView imgContactBack; // 好友列表返回按钮
    @Bind(R.id.btn_sure)
    TextView btnSure; // 确定选中好友
    @Bind(R.id.tv_line)
    TextView tvLine; // 确定选中好友
    @Bind(R.id.btn_modify_sure)
    TextView btnMoidfySure; // 确定修改群名称
    @Bind(R.id.iv_group_qr)
    ImageView ivGroupQr; //二维码
    @Bind(R.id.iv_group_head)
    ImageView ivGroupHead; //群头像
    @Bind(R.id.btn_delete_quit)
    Button btnDeleteQuit; // 删除群聊
    @Bind(R.id.img_group_back)
    ImageView back; //群聊返回键
    @Bind(R.id.img_modify_back)
    ImageView ivModifyBack; //群名称修改返回键
    @Bind(R.id.tv_selected_count)
    TextView tvSelectedCount;
    private WaitingDialog waitingDialog;
    private String groupId; //群组id
    private TakePicBottomPop mPopWindom;
    //根据用户userid键，储存user数据
    Map<String, RegisterUserNetBean> userMap = new HashMap<String, RegisterUserNetBean>();
    private List<RegisterUserNetBean> groupUsers; //增加移除群组成员后群组成员
    private Map<String, String> operationMap = new HashMap<>(); //储存移除或者添加新成员的userId
    private List<RegisterUserNetBean> contacts = new ArrayList<RegisterUserNetBean>(); //我的好友数据
    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO = 2;
    public static final int SELECT_PIC = 3;
    private GroupNetBean group;
    private Uri imageUri;
    private PermissionPopupWindow popupWindow;
    private PermissionPopupWindow failePopupWindow;
    private ConfirmPopupWindow quitWindow;
    private GroupContactListAdapter adapter;
    protected boolean isRemove = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_member);
        ButterKnife.bind(this);
        ActivityCollector.addActivity(GroupMemberActivity.this);

        groupId = getIntent().getStringExtra(GROUPID);
        // 初始化好友列表
        initContactDatas();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //当群成员扫码后，重新加载数据
        initGroupDatas();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (quitWindow != null && quitWindow.isShowing()) {
            quitWindow.dismiss();
        }
    }

    /**
     * 点击事件
     */
    private void initEvent() {
        rlAddContact.setOnClickListener(this);
        btnDeleteQuit.setOnClickListener(this);
        btnSure.setOnClickListener(this);
        imgContactBack.setOnClickListener(this);
        back.setOnClickListener(this);
        rlDownContact.setOnClickListener(this);
        llGroupName.setOnClickListener(this);
        rlGroupQr.setOnClickListener(this);
        rlGroupHead.setOnClickListener(this);
        ivModifyBack.setOnClickListener(this);
        btnMoidfySure.setOnClickListener(this);
        tvCheckAll.setOnClickListener(this);
    }

    /**
     * 初始化群聊界面数据
     */
    private void initGroupDatas() {

        if (waitingDialog == null) {
            waitingDialog = new WaitingDialog(this, "");
            waitingDialog.setText(getString(R.string.tip_loader));
            waitingDialog.show();
        } else {
            waitingDialog.show();
        }
        //当加载数据很慢，按返回键把dialog和activity都销毁
        waitingDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    dialog.dismiss();
                    ActivityCollector.removeActivity(GroupMemberActivity.this);
                    finish();
                    return true;
                } else {
                    return false;
                }
            }
        });
        llIndexContainer.setVisibility(View.VISIBLE);
        RequestUtils.findCommunityById(groupId, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
                waitingDialog.dismiss();
                showToast();
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                group = responseBean.getEntity(GroupNetBean.class);
                groupUsers = group.getUsers();
                userMap.clear();
                for (RegisterUserNetBean user : group.getUsers()) {
                    userMap.put(user.getUserId(), user);
                }
                //如果群主更改了群名称，头像，此时非群主走该方法
                if (group.getGroupOwnerId().equals(NetConfig.currentUser.getUserId())) {
                    tvLine.setVisibility(View.VISIBLE);
                    rlDownContact.setVisibility(View.VISIBLE);
                }
                tvGroupName.setText(group.getGroupName());
                Glide.with(MyApplication.getContext()).load(StringUtils.appendPicPath(
                        group.getGroupPic())).error(R.drawable.pic_head_defult).crossFade(1000).
                        into(ivGroupHead);
                // 初始化群成员表格
                initGroupMemberView();
                waitingDialog.dismiss();
            }
        });
    }

    /**
     * 初始化群成员列表
     */
    private void initGroupMemberView() {
        gvGroupMembers.setAdapter(new GroupMemberGridAdapter(groupUsers));
        gvGroupMembers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,
                    int i, long l) {
                Intent intent = new Intent(GroupMemberActivity.this, ContactIndexActivity.class);
                Gson gson = new Gson();
                intent.putExtra("data", gson.toJson(groupUsers.get(i)));
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化好友列表
     */
    private void initContactDatas() {
        //根据自己的id来查询好友数据
        findMyContacts();
    }

    /**
     * 查询我的好友，除了康尚百科和康尚客服
     */
    private void findMyContacts() {
        //每次进来联系清除，重新数据库获取
        contacts.clear();
        List<RegisterUserNetBean> friends = DatabaseHelper.getHelper(this).getRuntimeExceptionDao(
                RegisterUserNetBean.class).queryForEq("ownerId", NetConfig.currentUser.getUserId());

        for (RegisterUserNetBean bean : friends) {
            String userName = bean.getUserName();
            if (userName.equals(KSKF) || userName.endsWith(KSBK)) {
                continue;
            }
            contacts.add(bean);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.rl_add_group:
                if (showToast()) {
                    return;
                }
                //添加新成员
                isRemove = false;
                btnSure.setText(R.string.chat_invite);
                showContacts(2, userMap, contacts, group.getGroupOwnerId(), groupUsers);
                break;
            case R.id.rl_remove_group:
                //判断是否为群主
                if (showToast()) {
                    return;
                }
                if (group.getGroupOwnerId().equals(NetConfig.currentUser.getUserId())) {
                    //群主是否移除标志
                    showContacts(3, userMap, groupUsers, group.getGroupOwnerId(), groupUsers);
                    btnSure.setText(R.string.chat_remove);
                }
                break;
            case R.id.btn_modify_sure:
                if (showToast()) {
                    return;
                }
                isRemove = false;
                String groupName = editText.getText().toString().trim();
                if (TextUtils.isEmpty(groupName)) {
                    ToastUtils.toastContent(this, getString(R.string.tip_group_chat));
                    return;
                }

                updateGroupMember(groupName, group.getGroupPic());
                llContactContainer.setVisibility(View.GONE);
                llModifyContainer.setVisibility(View.GONE);
                llIndexContainer.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_group_name:
                //群名称,根据groupId来查询对应的群组信息
                if (showToast()) {
                    return;
                }
                if (group.getGroupOwnerId().equals(NetConfig.currentUser.getUserId())) {
                    llGroupName.setFocusableInTouchMode(false);
                    List<GroupNetBean> data = getLatestGroupData();
                    if (data != null && data.size() > 0) {
                        editText.setText(data.get(0).getGroupName());
                        editText.setSelection(data.get(0).getGroupName().length()); //设置光标在右边
                        llIndexContainer.setVisibility(View.GONE);
                        llContactContainer.setVisibility(View.GONE);
                        llModifyContainer.setVisibility(View.VISIBLE);
                    }
                } else {
                    showPermissionDialog();
                }

                break;
            case R.id.rl_group_qr:
                //二维码,根据groupId来查询对应的群组信息
                List<GroupNetBean> datas = getLatestGroupData();
                if (datas != null && datas.size() > 0) {
                    Intent intent = new Intent(GroupMemberActivity.this, QRCodeActivity.class);
                    intent.putExtra("from", true);
                    intent.putExtra("name", datas.get(0).getGroupId());
                    intent.putExtra("pic", datas.get(0).getGroupPic());
                    intent.putExtra("nick", datas.get(0).getGroupName());
                    startActivity(intent);
                }
                break;
            case R.id.rl_group_head:
                if (showToast()) {
                    return;
                }
                isRemove = false;
                //判断是否为群主
                if (group.getGroupOwnerId().equals(NetConfig.currentUser.getUserId())) {
                    addPhoto();
                } else {
                    showPermissionDialog();
                }

                break;
            case R.id.btn_delete_quit:
                if (showToast()) {
                    return;
                }
                isRemove = false;
                showDialog();
                break;
            case R.id.tv_check_all:
                if (showToast()) {
                    return;
                }
                if (group != null) {
                    //查看所有成员
                    Intent intent = new Intent(GroupMemberActivity.this, GroupMemberListActivity
                            .class);
                    intent.putExtra("groupId", group.getGroupId());
                    startActivity(intent);
                } else {
                    ToastUtils.toastContent(GroupMemberActivity.this, getString(R.string
                            .chat_unconnect));
                }

                break;
            case R.id.btn_sure:
                // 重新加载成员列表
                if (showToast()) {
                    return;
                }
                //得到键的集合
                Set<String> set = operationMap.keySet();
                // 遍历键的集合，获取得到每一个键
                for (String key : set) {
                    // 根据键去找值
                    String value = operationMap.get(key);
                    if (value.equals(Constants.GROUP_ADD)) {
                        //说明添加新的成员或者更新
                        isRemove = false;
                    } else {
                        isRemove = true;
                    }
                }
                initGroupMemberView();
                if (groupUsers.size() < 3) {
                    //成员不足3个时，提示
//                    isRemove = false;
                    ToastUtils.toastContent(MyApplication.getContext(), MyApplication
                            .getContext().getString(R.string.chat_delete_two));
                    return;
                }
                //网络获取新的群成员
                updateGroupMember(group.getGroupName(), group.getGroupPic());
                llContactContainer.setVisibility(View.GONE);
                llModifyContainer.setVisibility(View.GONE);
                llIndexContainer.setVisibility(View.VISIBLE);
                break;
            case R.id.img_contact_back:
                // 重新加载成员列表
                initGroupDatas();
                llContactContainer.setVisibility(View.GONE);
                llModifyContainer.setVisibility(View.GONE);
                llIndexContainer.setVisibility(View.VISIBLE);
                break;
            case R.id.img_group_back:
                waitingDialog.dismiss();
                ActivityCollector.removeActivity(GroupMemberActivity.this);
                finish();
                break;
            case R.id.img_modify_back:
                llContactContainer.setVisibility(View.GONE);
                llModifyContainer.setVisibility(View.GONE);
                llIndexContainer.setVisibility(View.VISIBLE);
                break;

            default:
                break;
        }
    }

    /**
     * 网络连接的提示
     * @return boolen 是否提示
     */
    private boolean showToast() {
        if (!RequestUtils.isNetworkConnected(GroupMemberActivity.this)) {
            ToastUtils.toastContent(GroupMemberActivity.this, getString(R.string.chat_unconnect));
            return true;
        }
        return false;
    }

    /**
     * 费群主弹出来dialog
     */
    private void showPermissionDialog() {
        popupWindow = new PermissionPopupWindow(this, new View
                .OnClickListener() {

            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 退群弹对话框
     */
    private void showDialog() {
        quitWindow = new ConfirmPopupWindow(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (quitWindow != null && quitWindow.isShowing()) {
                    quitWindow.dismiss();
                }
                quitChatGroup();
            }
        },
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (quitWindow != null && quitWindow.isShowing()) {
                            quitWindow.dismiss();
                        }
                    }
                });
        quitWindow.setTipsLayout(15, 60);
        quitWindow.setTitle("");
        quitWindow.setTips(getString(R.string.chat_group_quit));
        quitWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 退出群聊
     */
    private void quitChatGroup() {
        RequestUtils.quiteGroup(groupId, NetConfig.currentUser.getUserId(), new RequestCallback() {

            @Override
            public void onError(Call call, Exception e) {
                ToastUtils.toastContent(GroupMemberActivity.this, getString(R.string
                        .chat_quit_faile));
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                if (responseBean.getResultCode().equals(Constants.REQUEST_OK)) {

                    String msg = responseBean.getEntity(String.class);
                    if (msg != null) {
                        //解除群聊的主题，避免删除后还存在，删除本地数据库
                        removeLocal();
                        //自动跳转社区界面
                        ToastUtils.toastContent(GroupMemberActivity.this, msg);
                        ActivityCollector.finishAll();
                    } else {
                        ToastUtils.toastContent(GroupMemberActivity.this, msg);
                    }
                } else {
                    ToastUtils.toastContent(GroupMemberActivity.this, getString(R.string
                            .chat_quit_faile));
                }
            }
        });
    }

    /**
     * 清除数据
     */
    private void removeLocal() {
        removeLocalDb();
        removeMsg();
        removeNotice();
    }

    /**
     * 删除提醒
     */
    private void removeNotice() {
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(this)
                .getRuntimeExceptionDao(MqttMsgNotice.class);
        DeleteBuilder db = dao.deleteBuilder();
        try {
            db.where().eq("topicName", groupId).and().eq("ownerUserId", NetConfig.currentUser.
                    getUserId());
            dao.delete(db.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地聊天记录
     */
    private void removeMsg() {
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(this)
                .getRuntimeExceptionDao(MqttMsgBean.class);
        DeleteBuilder db = dao.deleteBuilder();
        try {
            db.where().eq("topicName", groupId).and().eq("ownerUserId", NetConfig.currentUser.
                    getUserId());
            dao.delete(db.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地群组
     */
    private void removeLocalDb() {

        try {
            Dao dao = DatabaseHelper.getHelper(this).getDao(GroupNetBean.class);
            DeleteBuilder db = dao.deleteBuilder();
            db.where().eq("groupId", groupId).and().eq("ownerId", NetConfig.
                    currentUser.getUserId());
            dao.delete(db.prepare());
            try {
                if (MqttService.mqttClient != null && MqttService.mqttClient.isConnected()) {

                    MqttService.mqttClient.unsubscribe(new String[]{groupId});
                }
            } catch (MqttException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得最新的数据库数据
     * @return 群组数据
     */
    private List<GroupNetBean> getLatestGroupData() {
        Dao dao = null;
        List<GroupNetBean> datas = null;
        try {
            dao = DatabaseHelper.getHelper(GroupMemberActivity.this).
                    getDao(GroupNetBean.class);
            QueryBuilder qb = dao.queryBuilder();
            qb.where().eq("groupId", groupId).and().eq("ownerId", NetConfig.
                    currentUser.getUserId());
            datas = dao.query(qb.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return datas;
    }

    /**
     * 点击添加图片，弹出popwindow。选择图库或拍照的图片。
     */
    private void addPhoto() {
        mPopWindom = new TakePicBottomPop(GroupMemberActivity.this, itemsOnClick);
        mPopWindom.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });
        mPopWindom.showAtLocation(GroupMemberActivity.this.ivGroupQr,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPopWindom.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    // 照相
                    clickTakePhoto();
                    break;
                case R.id.btn_album:
                    // 相册
                    clickAlbum();
                    break;
                case R.id.btn_cancel:
                    mPopWindom.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 点击相册（图库）
     */
    private void clickAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_PIC);
    }

    /**
     * 点击拍照
     */
    private void clickTakePhoto() {
        File outputImage = new File(Environment
                .getExternalStorageDirectory(), "test" + System
                .currentTimeMillis() + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        imageUri = Uri.fromFile(outputImage);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO); // 启动相机程序
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    sendPicture(imageUri.getEncodedPath());
                }
                break;

            case CROP_PHOTO:
                try {
                    if (resultCode == RESULT_OK) {
                        sendPicture(imageUri.getEncodedPath());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case SELECT_PIC:
                if (resultCode == RESULT_OK) {
                    sendPicture(PhotoUtils.getPath(this, data.getData()));
                } else {
                }
                break;
            default:
                break;
        }
    }

    /**
     * 显示图片
     * @param path 图片路径
     */
    private void sendPicture(String path) {
        PostFormBuilder builder = OkHttpUtils.post();
        ImageUtils imageUtils = new ImageUtils();
        //压缩后的图片
        Bitmap bitmap = imageUtils.ratio(path, 240f, 120f);
        byte[] bytes = imageUtils.getBitmapByte(bitmap);
        File file = new File(path);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        builder.addFile("file", "test+" + System.currentTimeMillis() + "" + ".jpg", file);

        String url = NetConfig.getBasicUrl() + "uploadPicture";
        builder.url(url)
                .build()
                .execute(new RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.toastContent(GroupMemberActivity.this, getString(R.string
                                .chat_update_group_faile));
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        ToastUtils.toastContent(GroupMemberActivity.this, getString(R.string
                                .chat_update_group_success));
                        String picPath = responseBean.getEntity(String.class);
                        String picUrl = StringUtils.appendPicPath(picPath);
                        //更改图片后重新设置值
                        group.setGroupPic(picPath);
                        //设置圆形图片
                        Glide.with(MyApplication.getContext()).load(picUrl).error(R.drawable.
                                pic_head_defult).crossFade(1000).into(ivGroupHead);
                        //重新保存新的群组
                        updateGroupMember(group.getGroupName(), group.getGroupPic());
                    }
                });
    }

    /**
     * 更新成员，头像，群名称到服务器
     * @param groupName 群名称
     * @param groupPic 群头像
     */
    private void updateGroupMember(final String groupName, final String groupPic) {
        String userIds = "";
        for (RegisterUserNetBean bean : groupUsers) {
            userIds += bean.getUserId() + ";";
        }
        RequestUtils.saveGroup(groupId, groupName, userIds, groupPic, group
                .getGroupOwnerId(), new RequestCallback() {
                    @Override
            public void onError(Call call, Exception e) {
                        ToastUtils.toastContent(GroupMemberActivity.this, getString(R.string.
                                chat_save_faile
                        ));
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        if (Constants.REQUEST_OK.equals(responseBean.getResultCode())) {
                            tvGroupName.setText(groupName);
                            if (isRemove) {
                                String diff = getDiffUserData(operationMap);
                                deleteGroupToDb(diff);
                            } else {
                                //服务器更新的，但是本地的也需要更新，由于服务器没有id
                                saveGroupToDb(groupName, groupPic);
                            }
                        }
                    }
                });
    }

    /**
     * @param map 操作数据的成员
     * @return 拿到移除的成员
     */
    private String getDiffUserData(Map<String, String> map) {

        StringBuffer buff = new StringBuffer();
        //得到键的集合
        if (map.size() > 0) {
            Set<String> set = map.keySet();
            // 遍历键的集合，获取得到每一个键
            for (String key : set) {
                buff.append("," + key);
            }
            return buff.toString();
        }
        return buff.toString();
    }

    /**
     * 移除群成员
     * @param diff 移除的userId数据
     */
    private void deleteGroupToDb(String diff) {
        //   给群组id发消息，移除的成员发送消息
        sendDeleteGroupMessage(diff);
    }

    /**
     * 移除群成员，发送群消息给群里的人
     * @param diffUsers 移除的数据
     */
    private void sendDeleteGroupMessage(String diffUsers) {
        //给群组id发消息，所有订阅群的都回收到
        String msgSendDate = DateUtils.getStringDateFormat(new Date(),
                DateUtils.yyyyMMddHHmmss);
        String targetType = MqttMsgUtils.MSG_TARGET_TYPE_GROUP;
        MqttMsgBean bean = new MqttMsgBean();
        bean.setMsgContent(groupId + diffUsers); //移除的人员
        bean.setMsgSendDate(msgSendDate);
        bean.setMsgTargetType(targetType);
        bean.setMsgType(MqttMsgUtils.MSG_TYPE_DELETE_GROUP);
        bean.setContact(NetConfig.currentUser.getUserId()); //谁发的消息
        bean.setTopicName(groupId); //群id

        try {
            byte[] msgContent = new RequestDeleteGroupMessageHandler().parseMessage(bean);
            MqttService.mqttClient.publish(groupId, msgContent, 2, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新成员，头像，群名称到本地数据库
     * @param groupName 群名称
     * @param groupPic 群头像
     */
    private void saveGroupToDb(String groupName, String groupPic) {
        Dao dao = null;
        try {
            dao = DatabaseHelper.getHelper(GroupMemberActivity.this).
                    getDao(GroupNetBean.class);
            //根据唯一的groupId查询本地的数据,然后在更新，如果根据setId来查询，是找不到
            QueryBuilder qb = dao.queryBuilder();
            qb.where().eq("groupId", groupId).and().eq("ownerId", NetConfig.
                    currentUser.getUserId());
            List<GroupNetBean> groups = dao.query(qb.prepare());
            if (groups != null && groups.size() > 0) {
                GroupNetBean bean = groups.get(0);
                bean.setGroupName(groupName);
                bean.setGroupPic(groupPic);
                bean.setGroupOwnerId(group.getGroupOwnerId());
                bean.setUsers(groupUsers); //设置群组成员集合
                dao.update(bean);
                //发送更新群的消息
                sendUpdateGroupMessage(bean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新完，发送群消息给群里的人
     * @param groupNetBean 群组信息
     */
    private void sendUpdateGroupMessage(GroupNetBean groupNetBean) {
//        //循环发送
        for (RegisterUserNetBean netBean : groupNetBean.getUsers()) {
            String msgSendDate = DateUtils.getStringDateFormat(new Date(),
                    DateUtils.yyyyMMddHHmmss);
            String targetType = MqttMsgUtils.MSG_TARGET_TYPE_GROUP;
            MqttMsgBean bean = new MqttMsgBean();
            bean.setMsgContent(groupNetBean.getGroupId());
            bean.setMsgSendDate(msgSendDate);
            bean.setMsgTargetType(targetType);
            bean.setMsgType(MqttMsgUtils.MSG_TYPE_REQUEST_GROUP);
            bean.setContact(NetConfig.currentUser.getUserId()); //谁发的消息
            bean.setTopicName(netBean.getUserName());

            try {
                byte[] msgContent = new RequestGroupReceivedMessageHandler().parseMessage(bean);
                MqttService.mqttClient.publish(bean.getTopicName(), msgContent, 2, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * +
     * 展示好友列表
     * @param i 1：建群 2： 已有群增加人 3:删除群成员
     * @param userMap 已有群成员map集合，来控制选择框
     * @param contacts 所有联系人
     * @param groupOwnerId 群主id
     * @param beforeGroupUsers 已有群成员，来显示群成员顺序，添加或者移除
     */
    private void showContacts(int i, Map<String, RegisterUserNetBean> userMap,
            List<RegisterUserNetBean> contacts, String groupOwnerId, List<RegisterUserNetBean>
            beforeGroupUsers) {
        tvSelectedCount.setText(R.string.chat_select_member);
        llIndexContainer.setVisibility(View.GONE);
        llModifyContainer.setVisibility(View.GONE);
        llContactContainer.setVisibility(View.VISIBLE);
        //每次进来清除当前的数据
        operationMap.clear();
        adapter = new GroupContactListAdapter(i, userMap, contacts, groupOwnerId,
                beforeGroupUsers, operationMap);
        lvContact.setAdapter(adapter);
        if (null != adapter) {
            adapter.setOnCbxStateChangedListener(new GroupContactListAdapter
                    .OnCbxStateChangedListener() {

                @Override
                public void onChange(int selectList) {
                    tvSelectedCount.setText(StringUtils.appendSelected(selectList));
                }
            });
        }
    }
}
